package com.casic.common.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.PoolableObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @author Li
 * @create 2019-04-17 11:44
 * @descriptions FTPClient 工厂类
 */
public class FTPClientFactory implements PoolableObjectFactory<FTPClient> {

    private FTPPoolConfig ftpPoolConfig;
    private static final Logger logger = LoggerFactory.getLogger(FTPClientFactory.class);


    public FTPClientFactory(FTPPoolConfig ftpPoolConfig) {
        this.ftpPoolConfig = ftpPoolConfig;
    }

    @Override
    public FTPClient makeObject() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(ftpPoolConfig.getConnectTimeout());
        try {
            ftpClient.connect(ftpPoolConfig.getHost(), ftpPoolConfig.getPort());
            //获得连接响应码
            int reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {

                logger.error("FTP 拒绝连接！");
                return null;
            }

            boolean result = ftpClient.login(ftpPoolConfig.getUsername(), ftpPoolConfig.getPassword());

            if(!result) {
                logger.error("FTP 登陆失败！");
                return null;
            }

            //ftpClient.setControlEncoding(ftpPoolConfig.getControlEncoding());
            ftpClient.setBufferSize(ftpPoolConfig.getBufferSize());
            ftpClient.setFileType(ftpPoolConfig.getFileType());
            ftpClient.setDataTimeout(ftpPoolConfig.getDataTimeout());
            ftpClient.setUseEPSVwithIPv4(ftpPoolConfig.isUseEPSVwithIPv4());
            if(ftpPoolConfig.isPassiveMode()) {
                ftpClient.enterLocalPassiveMode();
                logger.info("进入 FTP 被动模式");
            }
        } catch (IOException e) {
            logger.error("FTP 连接失败", e);
        }
        return ftpClient;
    }

    @Override
    public void destroyObject(FTPClient ftpClient) throws Exception {
        try {
            if(ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient != null) {
                // 注意,一定要在finally代码中断开连接，否则会导致占用ftp连接情况
                ftpClient.disconnect();
            }
        }
    }

    @Override
    public boolean validateObject(FTPClient ftpClient) {
        boolean connect = false;
        try {
            connect = ftpClient.sendNoOp();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connect;
    }

    @Override
    public void activateObject(FTPClient ftpClient) throws Exception {

    }

    @Override
    public void passivateObject(FTPClient ftpClient) throws Exception {

    }
}
